import { HttpClient } from '../utils/HttpClient';
import { HealthData, SleepData, AnalysisResult, ApiResponse } from '../types';

export class HealthDataService {
  private httpClient: HttpClient;

  constructor() {
    this.httpClient = new HttpClient();
  }

  /**
   * 获取最新的健康数据
   */
  public async getLatestHealthData(): Promise<HealthData> {
    try {
      const response = await this.httpClient.get<HealthData>('/health/latest');
      
      if (response.success && response.data) {
        return response.data;
      } else {
        throw new Error(response.message || '获取健康数据失败');
      }
    } catch (error) {
      console.error('Failed to get latest health data:', error);
      // 返回默认数据
      return this.getDefaultHealthData();
    }
  }

  /**
   * 获取指定日期范围的健康数据
   */
  public async getHealthDataByDateRange(
    startDate: string, 
    endDate: string
  ): Promise<HealthData[]> {
    try {
      const response = await this.httpClient.get<HealthData[]>('/health/range', {
        'Content-Type': 'application/json'
      });

      if (response.success && response.data) {
        return response.data;
      } else {
        return [];
      }
    } catch (error) {
      console.error('Failed to get health data by date range:', error);
      return [];
    }
  }

  /**
   * 获取睡眠数据
   */
  public async getSleepData(date: string): Promise<SleepData | null> {
    try {
      const response = await this.httpClient.get<SleepData>(`/health/sleep/${date}`);
      
      if (response.success && response.data) {
        return response.data;
      } else {
        return null;
      }
    } catch (error) {
      console.error('Failed to get sleep data:', error);
      return null;
    }
  }

  /**
   * 获取最近7天的睡眠数据
   */
  public async getWeeklySleepData(): Promise<SleepData[]> {
    try {
      const response = await this.httpClient.get<SleepData[]>('/health/sleep/weekly');
      
      if (response.success && response.data) {
        return response.data;
      } else {
        return [];
      }
    } catch (error) {
      console.error('Failed to get weekly sleep data:', error);
      return [];
    }
  }

  /**
   * 获取AI分析结果
   */
  public async getAnalysisResults(type?: string): Promise<AnalysisResult[]> {
    try {
      const url = type ? `/analysis/results?type=${type}` : '/analysis/results';
      const response = await this.httpClient.get<AnalysisResult[]>(url);
      
      if (response.success && response.data) {
        return response.data;
      } else {
        return [];
      }
    } catch (error) {
      console.error('Failed to get analysis results:', error);
      return [];
    }
  }

  /**
   * 获取健康趋势数据
   */
  public async getHealthTrends(days: number = 30): Promise<any> {
    try {
      const response = await this.httpClient.get(`/health/trends?days=${days}`);
      
      if (response.success && response.data) {
        return response.data;
      } else {
        return this.getDefaultTrendsData();
      }
    } catch (error) {
      console.error('Failed to get health trends:', error);
      return this.getDefaultTrendsData();
    }
  }

  /**
   * 同步健康数据
   */
  public async syncHealthData(data: Partial<HealthData>): Promise<boolean> {
    try {
      const response = await this.httpClient.post('/health/sync', data);
      return response.success;
    } catch (error) {
      console.error('Failed to sync health data:', error);
      return false;
    }
  }

  /**
   * 计算BMI
   */
  public calculateBMI(height: number, weight: number): number {
    if (height <= 0 || weight <= 0) return 0;
    const heightInMeters = height / 100;
    return Number((weight / (heightInMeters * heightInMeters)).toFixed(1));
  }

  /**
   * 获取BMI状态
   */
  public getBMIStatus(bmi: number): { status: string; color: string; description: string } {
    if (bmi < 18.5) {
      return { status: '偏瘦', color: '#34C759', description: '建议增加营养摄入' };
    } else if (bmi < 24) {
      return { status: '正常', color: '#007AFF', description: '保持良好的生活习惯' };
    } else if (bmi < 28) {
      return { status: '超重', color: '#FF9500', description: '建议控制饮食和增加运动' };
    } else {
      return { status: '肥胖', color: '#FF3B30', description: '建议咨询医生制定减重计划' };
    }
  }

  /**
   * 获取心率状态
   */
  public getHeartRateStatus(heartRate: number, age: number): { status: string; color: string } {
    const maxHeartRate = 220 - age;
    const restingMin = 60;
    const restingMax = 100;

    if (heartRate < restingMin) {
      return { status: '偏低', color: '#34C759' };
    } else if (heartRate <= restingMax) {
      return { status: '正常', color: '#007AFF' };
    } else if (heartRate <= maxHeartRate * 0.7) {
      return { status: '偏高', color: '#FF9500' };
    } else {
      return { status: '过高', color: '#FF3B30' };
    }
  }

  /**
   * 获取睡眠质量评级
   */
  public getSleepQualityRating(score: number): { rating: string; color: string; description: string } {
    if (score >= 90) {
      return { rating: '优秀', color: '#34C759', description: '睡眠质量很好' };
    } else if (score >= 80) {
      return { rating: '良好', color: '#007AFF', description: '睡眠质量不错' };
    } else if (score >= 70) {
      return { rating: '一般', color: '#FF9500', description: '睡眠质量有待改善' };
    } else if (score >= 60) {
      return { rating: '较差', color: '#FF6B35', description: '睡眠质量需要改善' };
    } else {
      return { rating: '很差', color: '#FF3B30', description: '睡眠质量急需改善' };
    }
  }

  /**
   * 格式化睡眠时长
   */
  public formatSleepDuration(minutes: number): string {
    if (minutes <= 0) return '--';
    
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    
    if (hours === 0) {
      return `${mins}分钟`;
    } else if (mins === 0) {
      return `${hours}小时`;
    } else {
      return `${hours}小时${mins}分钟`;
    }
  }

  /**
   * 格式化距离
   */
  public formatDistance(meters: number): string {
    if (meters < 1000) {
      return `${Math.round(meters)}米`;
    } else {
      return `${(meters / 1000).toFixed(1)}公里`;
    }
  }

  /**
   * 获取默认健康数据（用于离线或错误情况）
   */
  private getDefaultHealthData(): HealthData {
    return {
      userId: '',
      date: new Date().toISOString().split('T')[0],
      steps: 0,
      sleepDuration: 0,
      sleepScore: 0,
      deepSleep: 0,
      heartRate: [],
      averageHeartRate: 0,
      stressLevel: 0,
      calories: 0,
      distance: 0,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
  }

  /**
   * 获取默认趋势数据
   */
  private getDefaultTrendsData(): any {
    return {
      steps: { trend: 'stable', change: 0 },
      sleep: { trend: 'stable', change: 0 },
      heartRate: { trend: 'stable', change: 0 },
      stress: { trend: 'stable', change: 0 }
    };
  }
}